#include <TJpg_Decoder.h>
#include <SPI.h>
#include <TFT_eSPI.h>

#define GFXFF 1
#define FSB9 &FreeSerifBold9pt7b

TFT_eSPI tft = TFT_eSPI();

bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap)
{
  // Stop further decoding as image is running off bottom of screen
  if ( y >= tft.height() ) return 0;

  // This function will clip the image block rendering automatically at the TFT boundaries
  tft.pushImage(x, y, w, h, bitmap);

  // This might work instead if you adapt the sketch to use the Adafruit_GFX library
  // tft.drawRGBBitmap(x, y, bitmap, w, h);

  // Return 1 to decode next block
  return 1;
}

// refreshBg: 是否刷新背景； clearText:是否清空Text
void printText(String text, bool refreshBg, bool clearText) {
  if (refreshBg) {
    tft.fillScreen(TFT_BLACK);
  }
  if (clearText) {
    tft.setCursor(5, 5, 2);
    tft.setRotation(1);
  }
  tft.println(text);
}

void initTFT_Screen() {
  Serial.println("INIT DISPLAY");
  tft.begin();
  tft.fillScreen(TFT_BLACK);
  // 设置文本颜色为白色，黑色文本背景
  tft.setTextColor(TFT_GREEN);
  tft.setCursor(5, 5, 2);
  tft.setRotation(1);

  TJpgDec.setJpgScale(1);
  TJpgDec.setSwapBytes(true);
  TJpgDec.setCallback(tft_output);

  delay(3000);
  printText("Initializing Screen...", false, false);
}

camera_fb_t* capture() {
  camera_fb_t *fb = NULL;
  esp_err_t res = ESP_OK;
  fb = esp_camera_fb_get();
  return fb;
}

void tft_display() {
  camera_fb_t *fb = capture();
  if (!fb || fb->format != PIXFORMAT_JPEG) {
    Serial.println("Camera capture failed");
    esp_camera_fb_return(fb);
    return;
  } else {
    TJpgDec.drawJpg(0, 0, (const uint8_t*)fb->buf, fb->len);
    esp_camera_fb_return(fb);
  }
}
